package cn.always.xiajia.framework.rpc.config;

import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClientSpecification;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

import cn.always.xiajia.framework.common.config.RpcProperties;
import cn.always.xiajia.framework.common.config.SecurityProperties;
import cn.always.xiajia.framework.rpc.core.fegin.RfqLoadBalancerClientFactory;
import cn.always.xiajia.framework.rpc.core.fegin.RfqRequestInterceptor;

@AutoConfiguration
@EnableConfigurationProperties({ RpcProperties.class, SecurityProperties.class })
public class XiaJiaRpcAutoConfiguration {

	@Resource
	private SecurityProperties securityProperties;

	@Resource
	private RpcProperties properties;

	/**
	 * 透传数据给feign
	 * 
	 * @return
	 */
	@Bean
	public RfqRequestInterceptor rfqRequestInterceptor() {
		return new RfqRequestInterceptor(securityProperties, properties);
	}

	@Bean
	@LoadBalanced // 开启负载均衡能力
	public RestTemplate restTemplate(RestTemplateBuilder builder) {
		return builder.build();
	}

	/**
	 * 创建 {@link EnvLoadBalancerClientFactory} Bean 参考
	 * {@link LoadBalancerAutoConfiguration#loadBalancerClientFactory( LoadBalancerClientsProperties)}
	 * 方法
	 */
	@Bean
	public LoadBalancerClientFactory loadBalancerClientFactory(LoadBalancerClientsProperties properties,
			ObjectProvider<List<LoadBalancerClientSpecification>> configurations) {
		RfqLoadBalancerClientFactory clientFactory = new RfqLoadBalancerClientFactory(properties);
		clientFactory.setConfigurations(configurations.getIfAvailable(Collections::emptyList));
		return clientFactory;
	}

}
